package com.xdtech.trans.service.impl;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xdtech.common.utils.DateUtil;
import com.xdtech.common.utils.EmptyUtil;
import com.xdtech.common.utils.DateUtil.DateStyle;
import com.xdtech.core.dao.BaseDao;
import com.xdtech.core.model.BaseItem;
import com.xdtech.core.orm.Page;
import com.xdtech.core.orm.utils.BeanUtils;
import com.xdtech.trans.dao.TransOrderScanDao;
import com.xdtech.trans.model.TransAccount;
import com.xdtech.trans.model.TransOrder;
import com.xdtech.trans.model.TransOrderScan;
import com.xdtech.trans.model.TransWebSite;
import com.xdtech.trans.service.PriceConfigService;
import com.xdtech.trans.service.TransAccountService;
import com.xdtech.trans.service.TransAccountTradeService;
import com.xdtech.trans.service.TransOrderScanService;
import com.xdtech.trans.service.TransOrderService;
import com.xdtech.trans.service.TransOrderTrackService;
import com.xdtech.trans.service.TransWebSiteService;
import com.xdtech.trans.util.TransConstants;
import com.xdtech.trans.vo.PriceConfigItem;
import com.xdtech.trans.vo.TransOrderScanItem;
import com.xdtech.web.model.Pagination;

/**
 * 
 * @author max.zheng
 * @create 2015-06-08 23:17:52
 * @since 1.0
 * @see
 */
@Service
public class TransOrderScanServiceImpl implements TransOrderScanService {
	private Log log = LogFactory.getLog(TransOrderScanServiceImpl.class);
	@Autowired
	private TransOrderScanDao transOrderScanDao;
	@Autowired
	private BaseDao baseDao;
	@Autowired
	private TransWebSiteService transWebSiteService;
	@Autowired
	private TransOrderTrackService transOrderTrackService;
	@Autowired
	private TransOrderService transOrderService;
	@Autowired
	private PriceConfigService priceConfigService;
	@Autowired
	private TransAccountService transAccountService;
	@Autowired
	private TransAccountTradeService transAccountTradeService;
	/**
	 * @description
	 * @author max.zheng
	 * @create 2015-06-08 23:17:52
	 * @modified by
	 * @param entity
	 */
	public void save(TransOrderScan entity) {
		transOrderScanDao.save(entity);
	}
	/**
	 * @description
	 * @author max.zheng
	 * @create 2015-06-08 23:17:52
	 * @modified by
	 * @param entity
	 */
	public void saveAll(List<TransOrderScan> entities) {
		transOrderScanDao.saveAll(entities);
	}

	/**
	 * @description
	 * @author max.zheng
	 * @create 2015-06-08 23:17:52
	 * @modified by
	 * @param entity
	 */
	public void delete(TransOrderScan entity) {
		transOrderScanDao.delete(entity);
	}

	/**
	 * @description
	 * @author max.zheng
	 * @create 2015-06-08 23:17:52
	 * @modified by
	 * @param id
	 */
	public void delete(Long id) {
		transOrderScanDao.delete(id);
	}

	/**
	 * @description
	 * @author max.zheng
	 * @create 2015-06-08 23:17:52
	 * @modified by
	 * @param id
	 * @return
	 */
	public TransOrderScan get(Long id) {
		return transOrderScanDao.get(id);
	}

	/**
	 * @description
	 * @author max.zheng
	 * @create 2015-06-08 23:17:52
	 * @modified by
	 * @return
	 */
	public List<TransOrderScan> getAll() {
		return transOrderScanDao.getAll();
	}

	/**
	 * @description
	 * @author max.zheng
	 * @create 2015-06-08 23:17:52
	 * @modified by
	 * @param pg
	 * @param values
	 * @return
	 */
	public Map<String, Object> loadPageAndCondition(Pagination pg,
			Map<String, String> values) {
		Map<String, Object> results = new HashMap<String, Object>();
		List<Object> transOrderScans = null;
		long rows = 0;
		if (pg!=null) {
			Page<TransOrderScan> page = transOrderScanDao.findPage(pg,"from TransOrderScan order by createTime desc", values);
			transOrderScans = BeanUtils.copyListProperties(
					TransOrderScanItem.class, page.getResult());
			rows = page.getTotalItems();
		}else {
			List<TransOrderScan> transOrderScanList = transOrderScanDao.find("from TransOrderScan order by id desc", values);
			transOrderScans = BeanUtils.copyListProperties(
					TransOrderScanItem.class, transOrderScanList);
			rows = transOrderScans.size();
		}
		results.put("total", rows);
		results.put("rows", transOrderScans);
		return results;
	}

	/**
	 * @description
	 * @author max.zheng
	 * @create 2015-06-08 23:17:52
	 * @modified by
	 * @param item
	 * @return
	 */
	public boolean saveOrUpdateTransOrderScan(TransOrderScanItem item) {
		TransOrderScan transOrderScan = null;
		if (item.getId()==null) {
			transOrderScan = new TransOrderScan();
		}else {
			transOrderScan = transOrderScanDao.get(item.getId());
		}
		//复制前台修改的属性
		BeanUtils.copyProperties(transOrderScan, item);
		transOrderScanDao.save(transOrderScan);
		return true;
	}

	/**
	 * @description
	 * @author max.zheng
	 * @create 2015-06-08 23:17:52
	 * @modified by
	 * @param transOrderScanId
	 * @return
	 */
	public TransOrderScanItem loadTransOrderScanItem(Long transOrderScanId) {
		TransOrderScan transOrderScan = transOrderScanDao.get(transOrderScanId);
		return TransOrderScanItem.createItem(transOrderScan);
	}

	/**
	 * @description
	 * @author max.zheng
	 * @create 2015-06-08 23:17:52
	 * @modified by
	 * @param id
	 * @return
	 */
	public boolean deleteTransOrderScanInfo(long id) {
		delete(id);
		return true;
	}
	
	/**
	 * @description
	 * @author max.zheng
	 * @create 2015-06-08 23:17:52
	 * @modified by
	 * @param newIds
	 * @return
	 */
	public boolean deleteTransOrderScanInfo(List<Long> transOrderScanIds) {
		for (Long id : transOrderScanIds) {
			delete(id);
		}
		return true;
	}
	
	public Map<String, Object> loadPageDataByConditions(Pagination pg,
			BaseItem baseItem, String queryName) {
		Map<String, Object> results = new HashMap<String, Object>();
		Page page = baseDao.findPageByNamedQuery(pg, queryName,baseItem);
		results.put("total", page.getTotalItems());
		results.put("rows", page.getResult());
		return results;
	}
	/**
	 * @description
	 * @author max.zheng
	 * @create 2015-06-08 23:17:52
	 * @modified by
	 * @return
	 */
	@Override
	public List<TransOrderScanItem> loadItems() {
		List<TransOrderScan> transOrderScans = getAll();
		return TransOrderScanItem.createItems(transOrderScans);
	}
	/**
	 * @description
	 * @author max.zheng
	 * @create 2015-6-9下午10:28:10
	 * @modified by
	 * @param item
	 */
	@Override
	public String sureStartScan(TransOrderScanItem item) {
		boolean checkIsSign = checkOrderIsSign(item.getOrderNo());
		if (checkIsSign) {
			return "运单已完成签收录入，无法寄件扫描.";
		}else {
			TransOrderScan transOrderScan = createScanInfoFromOrder(item);
			if (null == transOrderScan)
			{
				return "查询扫描运单信息不存在";
			}
			if (item.getCurrentWebsiteId()!=null) {
				TransWebSite startTransWebSite = transWebSiteService.get(item.getCurrentWebsiteId());
				transOrderScan.setStartWebsite(startTransWebSite.getName());
				transOrderScan.setStartWebsiteId(startTransWebSite.getId());
				transOrderScan.setCurrentWebsite(startTransWebSite.getName());
				transOrderScan.setCurrentWebsiteId(startTransWebSite.getId());
			}
			
			transOrderScanDao.save(transOrderScan);
			//添加跟踪信息
			transOrderTrackService.startTrack(transOrderScan);
			//变更运单状态 为等待发件
			transOrderService.updateOrderStatuByNo(item.getOrderNo(),TransConstants.ORDER_STATUS_WAITE_SEND);
			return "";
		}
		
	}
	/**
	 * 检测是否已经签收扫描
	 * @author max.zheng
	 * @create 2015-7-29下午10:01:57
	 * @modified by
	 * @param orderNo
	 * @return
	 */
	private boolean checkOrderIsSign(String orderNo) {
		TransOrder transOrder = transOrderService.getOrderByNo(orderNo);
		return TransConstants.ORDER_STATUS_RETURN.equals(transOrder.getOrderStatus());
	}
	/* (非 Javadoc)
	 * sureSendScan
	 * <p>对override方法的补充说明，若不需要则删除此行</p>
	 * 
	 * @param item
	 * @see com.xdtech.trans.service.TransOrderScanService#sureSendScan(com.xdtech.trans.vo.TransOrderScanItem)
	 */
	@Override
	public String sureSendScan(TransOrderScanItem item)
	{
		boolean checkIsSign = checkOrderIsSign(item.getOrderNo());
		if (checkIsSign) {
			return "运单已完成签收录入，无法发件扫描.";
		}else {
			TransOrderScan transOrderScan = createScanInfoFromOrder(item);
			if (null == transOrderScan)
			{
				return "查询扫描运单信息不存在";
			}
			//上一站地址
			if (item.getPreviousWebsiteId()!=null)
			{
				TransWebSite previousTransWebSite = transWebSiteService.get(Long.valueOf(item.getPreviousWebsiteId()));
				transOrderScan.setPreviousWebsite(previousTransWebSite.getName());
				transOrderScan.setPreviousWebsiteId(previousTransWebSite.getId());
			}
			//下一站地址
			if (item.getNextWebsiteId()!=null)
			{
				TransWebSite nextTransWebSite = transWebSiteService.get(Long.valueOf(item.getNextWebsiteId()));
				transOrderScan.setNextWebsite(nextTransWebSite.getName());
				transOrderScan.setNextWebsiteId(nextTransWebSite.getId());
			}
			//当前网点
			if (item.getCurrentWebsiteId()!=null)
			{
				TransWebSite currentTransWebSite = transWebSiteService.get(Long.valueOf(item.getCurrentWebsiteId()));
				transOrderScan.setCurrentWebsite(currentTransWebSite.getName());
				transOrderScan.setCurrentWebsiteId(currentTransWebSite.getId());
			}
			//司机
			transOrderScan.setDriver(item.getDriver());
			transOrderScan.setDriverPhone(item.getDriverPhone());
			transOrderScan.setCarNum(item.getCarNum());
			transOrderScanDao.save(transOrderScan);
			//下一站地址
			//添加跟踪信息
			transOrderTrackService.sendTrack(transOrderScan);
			//变更运单状态 为等待发件
			transOrderService.updateOrderStatuByNo(item.getOrderNo(),TransConstants.ORDER_STATUS_SEND);
			return "";
		}
		
	}
	/**
	 * 
	 * @author max.zheng
	 * @create 2015-6-11下午11:17:56
	 * @modified by
	 * @param item
	 * @return
	 */
	private TransOrderScan createScanInfoFromOrder(TransOrderScanItem item) {
		TransOrderScan transOrderScan = null;
		TransOrder transOrder = transOrderService.getOrderByNo(item.getOrderNo());
		if (null != transOrder)
		{
			transOrderScan = new TransOrderScan();
			BeanUtils.copyProperties(transOrderScan, transOrder);
			//设置记录创建人
			transOrderScan.setCreator(item.getCreator());
			//设置扫描人
			transOrderScan.setScanOperator(item.getScanOperator());
			//设置扫描时间
			transOrderScan.setScanTime(item.getScanTime());
			transOrderScan.setScanType(item.getScanType());
			//设置扫描来源
			transOrderScan.setScanFrom(item.getScanFrom());
			//重置id为空
			transOrderScan.setId(null);
			if (StringUtils.isNotBlank(transOrder.getEndWebsiteId()+"")) {
				TransWebSite endTransWebSite = transWebSiteService.get(transOrder.getEndWebsiteId());
				//目的地址
				transOrderScan.setEndWebsite(endTransWebSite.getName());
				transOrderScan.setEndWebsiteId(endTransWebSite.getId());
			}
			//寄件网点
			if (StringUtils.isNotBlank(item.getStartWebsiteId()+"")) {
				TransWebSite startTransWebSite = transWebSiteService.get(item.getStartWebsiteId());
				transOrderScan.setStartWebsite(startTransWebSite.getName());
				transOrderScan.setStartWebsiteId(startTransWebSite.getId());
			}
		}else
		{
			log.error("查询单号为空，orderNo="+item.getOrderNo());
		}
		return transOrderScan;
	}
	/* (非 Javadoc)
	 * arriveStartScan
	 * <p>对override方法的补充说明，若不需要则删除此行</p>
	 * 
	 * @param item
	 * @see com.xdtech.trans.service.TransOrderScanService#arriveStartScan(com.xdtech.trans.vo.TransOrderScanItem)
	 */
	@Override
	public String sureArriveScan(TransOrderScanItem item)
	{
		boolean checkIsSign = checkOrderIsSign(item.getOrderNo());
		if (checkIsSign) {
			return "运单已完成签收录入，无法到件扫描.";
		}else {
			TransOrderScan transOrderScan = createScanInfoFromOrder(item);
			if (null == transOrderScan)
			{
				return "查询扫描运单信息不存在";
			}
			//上一站地址
			if (item.getPreviousWebsiteId()!=null)
			{
				TransWebSite previousTransWebSite = transWebSiteService.get(Long.valueOf(item.getPreviousWebsiteId()));
				transOrderScan.setPreviousWebsite(previousTransWebSite.getName());
				transOrderScan.setPreviousWebsiteId(item.getPreviousWebsiteId());
			}
			//当前网点
			if (item.getCurrentWebsiteId()!=null)
			{
				TransWebSite currentTransWebSite = transWebSiteService.get(Long.valueOf(item.getCurrentWebsiteId()));
				transOrderScan.setCurrentWebsite(currentTransWebSite.getName());
				transOrderScan.setCurrentWebsiteId(currentTransWebSite.getId());
			}
			//设置司机相关信息
			transOrderScan.setDriver(item.getDriver());
			transOrderScan.setDriverPhone(item.getDriverPhone());
			transOrderScan.setCarNum(item.getCarNum());
			transOrderScanDao.save(transOrderScan);
			//添加跟踪信息
			transOrderTrackService.arriveTrack(transOrderScan);
//			//变更运单状态 为等待发件
//			transOrderService.updateOrderStatuByNo(item.getOrderNo(),TransConstants.ORDER_STATUS_WAITE_SEND);
			return "";
		}
		
	}
	/* (非 Javadoc)
	 * sureDeliveryScan
	 * <p>对override方法的补充说明，若不需要则删除此行</p>
	 * 
	 * @param item
	 * @see com.xdtech.trans.service.TransOrderScanService#sureDeliveryScan(com.xdtech.trans.vo.TransOrderScanItem)
	 */
	@Override
	public String sureDeliveryScan(TransOrderScanItem item)
	{
		boolean checkIsSign = checkOrderIsSign(item.getOrderNo());
		if (checkIsSign) {
			return "运单已完成签收录入，无法派件扫描.";
		}else {
			TransOrderScan transOrderScan = createScanInfoFromOrder(item);
			if (null == transOrderScan)
			{
				return "查询扫描运单信息不存在";
			}
			if (item.getStartWebsiteId()!=null) {
				TransWebSite startTransWebSite = transWebSiteService.get(item.getStartWebsiteId());
				transOrderScan.setStartWebsite(startTransWebSite.getName());
				transOrderScan.setStartWebsiteId(startTransWebSite.getId());
			}
			//设置当前网点
			TransWebSite currentTransWebSite = transWebSiteService.get(item.getCurrentWebsiteId());
			transOrderScan.setCurrentWebsite(currentTransWebSite.getName());
			transOrderScan.setCurrentWebsiteId(Long.valueOf(item.getCurrentWebsiteId()));
			//设置派件信息
			transOrderScan.setDeliveryName(item.getDeliveryName());
			transOrderScan.setDeliveryPhone(item.getDeliveryPhone());
			transOrderScanDao.save(transOrderScan);
			
			//添加跟踪信息
			transOrderTrackService.deliveryTrack(transOrderScan);
			//变更运单状态 为派件中
			transOrderService.updateOrderStatuByNo(item.getOrderNo(),TransConstants.ORDER_STATUS_DELIVERY);
			return "";
		}
		
	}
	/**
	 * 
	 * @author <a href="max.zheng@zkteco.com">郑志雄</>
	 * @since 2015-7-6 上午10:35:18
	 */
	private void handleDeliveryLink(TransWebSite currentTransWebSite,TransOrderScan transOrderScan)
	{
		PriceConfigItem priceConfigItem = priceConfigService.loadFirstPriceConfigItem();
		if (null != priceConfigItem&&"false".equals(priceConfigItem.getIsTargetDEliver()))
		{
			//非目的地派件
			//账户
			TransAccount transAccount = transAccountService.getPayAccountByWebsiteId(currentTransWebSite.getId());
			double money = 0;
			TransOrder transOrder = transOrderService.getOrderByNo(transOrderScan.getOrderNo());
			if (transOrder.getWeight()>priceConfigItem.getFirstWeight())
			{
				money = (priceConfigItem.getLinkPrice()+(transOrder.getWeight()-priceConfigItem.getFirstWeight())*priceConfigItem.getAddDeliveryPrice());
			}else
			{
				money = priceConfigItem.getDeliveryPrice();
			}
			//创建交易记录	派件
			transAccountTradeService.createTransTradeRecord(transAccount,money,TransConstants.TRADE_DELIVERY,transOrderScan.getScanOperator(),transOrderScan.getOrderNo(),true);
		}
	}
	/* (非 Javadoc)
	 * sureSignScan
	 * <p>对override方法的补充说明，若不需要则删除此行</p>
	 * 
	 * @param item
	 * @see com.xdtech.trans.service.TransOrderScanService#sureSignScan(com.xdtech.trans.vo.TransOrderScanItem)
	 */
	@Override
	public String sureSignScan(TransOrderScanItem item)
	{
		boolean checkIsSign = checkOrderIsSign(item.getOrderNo());
		if (checkIsSign) {
			return "运单已完成签收录入，无需再次签收录入.";
		}else {
			TransOrder transOrder = transOrderService.getOrderByNo(item.getOrderNo());
			if (TransConstants.ORDER_STATUS_RETURN.equals(transOrder.getOrderStatus())) {
				return item.getOrderNo()+"已回单";
			}
			TransOrderScan transOrderScan = createScanInfoFromOrder(item);
			//设置签收信息
			transOrderScan.setSignName(item.getSignName());
			transOrderScan.setSignTime(item.getScanTime());
			transOrderScan.setSignStatus(item.getSignStatus());	
			transOrderScanDao.save(transOrderScan);
			//添加跟踪信息
			transOrderTrackService.signTrack(transOrderScan);
			//变更运单状态 为回单
			transOrderService.updateOrderStatuByNo(item.getOrderNo(),TransConstants.ORDER_STATUS_RETURN);
			//费用计算
			
			//当前登录用户账户
			TransAccount currentTransAccount = transAccountService.getPayAccountByWebsiteId(item.getCurrentWebsiteId());
			//费用结算
			transOrderService.handleLinkInfo(transOrder, item.getScanOperator(), currentTransAccount);
			return "";
		}
		
	}
	/* (非 Javadoc)
	 * loadLastestScanInfoByOrderNo
	 * <p>对override方法的补充说明，若不需要则删除此行</p>
	 * 
	 * @param orderNo
	 * @return
	 * @see com.xdtech.trans.service.TransOrderScanService#loadLastestScanInfoByOrderNo(java.lang.String)
	 */
	@Override
	public TransOrderScanItem loadLastestScanInfoByOrderNo(String orderNo)
	{
		List<TransOrderScan> transOrderScans = transOrderScanDao.findByHql("from TransOrderScan where orderNo=? order by id desc", orderNo);
		TransOrderScanItem item = null;
		if (EmptyUtil.isNotEmpty(transOrderScans))
		{
			item = TransOrderScanItem.createItem(transOrderScans.get(0));
			TransWebSite tempWebSite = null;
			//设置寄件网点信息
			if (null != item.getStartWebsiteId())
			{
				tempWebSite = transWebSiteService.get(item.getStartWebsiteId());
				item.setStartWebsite(tempWebSite.getName());
				item.setStartWebsiteId(tempWebSite.getId());
			}
			//设置目的网点信息
			if (null != item.getEndWebsiteId())
			{
				tempWebSite = transWebSiteService.get(item.getEndWebsiteId());
				item.setEndWebsite(tempWebSite.getName());
				item.setEndWebsiteId(tempWebSite.getId());
			}
			//设置上一站网点信息
			if (null != item.getCurrentWebsiteId())
			{
				tempWebSite = transWebSiteService.get(item.getCurrentWebsiteId());
				item.setPreviousWebsite(tempWebSite.getName());
				item.setPreviousWebsiteId(tempWebSite.getId());
			}
			//设置下一站网点信息
			if (null != item.getNextWebsiteId())
			{
				tempWebSite = transWebSiteService.get(item.getNextWebsiteId());
				item.setNextWebsite(tempWebSite.getName());
				item.setNextWebsiteId(tempWebSite.getId());
			}
			item.setScanTime(DateUtil.getDate(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
			item.setSignTime(DateUtil.getDate(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
		}
		return item;
	}
	/* (非 Javadoc)
	 * deliverScanWithApp
	 * <p>对override方法的补充说明，若不需要则删除此行</p>
	 * 
	 * @param transOrderScanItem
	 * @return
	 * @see com.xdtech.trans.service.TransOrderScanService#deliverScanWithApp(com.xdtech.trans.vo.TransOrderScanItem)
	 */
	@Override
	public String deliverScanWithApp(TransOrderScanItem transOrderScanItem)
	{
		TransWebSite currentWebSite = transWebSiteService.getWebsiteByName(transOrderScanItem.getCurrentWebsite());
		transOrderScanItem.setCurrentWebsite(currentWebSite.getName());
		transOrderScanItem.setCurrentWebsiteId(currentWebSite.getId());
		//start 也是当前网点
		transOrderScanItem.setStartWebsiteId(currentWebSite.getId());
		transOrderScanItem.setStartWebsite(currentWebSite.getName());
		//派件扫描
		transOrderScanItem.setScanType(TransConstants.SCAN_TYPE_DELIVERY);
		String rs = sureDeliveryScan(transOrderScanItem);
		if (StringUtils.isNotBlank(rs))
		{
			log.info("APP派件扫描：" + rs+",操作结果："+StringUtils.isBlank(rs));
			return rs;
		}else
		{
			transOrderScanItem.setScanType(TransConstants.SCAN_TYPE_SIGN);
			//产生签收信息
			transOrderScanItem.setScanTime(DateUtil.getDate(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
			rs = sureSignScan(transOrderScanItem);
			log.info("APP签收扫描：" + rs+",操作结果："+StringUtils.isBlank(rs));
		}
		return rs;
	}
}
